using System;
using System.Collections.Generic;
using System.Linq;
using Lucene.Net.Index;

namespace LuceneSearch.ContactApp.Indexing
{
    public class EntityIndexRemover : IEntityIndexProcessor
    {
        private readonly IndexDirectoryProvider directoryProvider;

        public EntityIndexRemover(IndexDirectoryProvider directoryProvider)
        {
            this.directoryProvider = directoryProvider;
        }

        public bool CanProcess(IndexWorkType indexWorkType)
        {
            return indexWorkType == IndexWorkType.Delete;
        }

        public void Process(IEnumerable<object> entities)
        {
            var typeGroups = entities.GroupBy(x => x.GetType());

            foreach (var typeGroup in typeGroups)
            {
                RemoveIndexForSameType(typeGroup);
            }
        }

        private void RemoveIndexForSameType(IGrouping<Type, object> typeGroup)
        {
            var directory = directoryProvider.GetIndexDirectoryForType(typeGroup.Key);

            if (!IndexReader.IndexExists(directory)) return;

            IndexReader reader = null;

            try
            {
                reader = IndexReader.Open(directory);

                foreach (var entity in typeGroup)
                {
                    var term = new Term("Id", entity.GetIndexValue("Id"));
                    reader.DeleteDocuments(term);
                }
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
    }
}